<template>
  <div>
    <div>&nbsp;&nbsp;</div>
    <div>&nbsp;&nbsp;</div>
    <div>
      <van-pull-refresh v-model="isLoading" @refresh="onRefresh">
        <div ref="main" class="message">
          <div ref="content">
            <ul>
              <li
                v-for="msg in messages"
                :key="msg.id"
                :class="
                  align(msg) === 'self' ? 'an-move-right' : 'an-move-left'
                "
              >
                <!-- {{ msg.id }} -->
                <p class="time">
                  <span v-text="format_date(msg)" />
                </p>

                <div :class="align(msg)">
                  <img
                    class="avatar"
                    width="45"
                    height="45"
                    :src="get_image(msg)"
                  >

                  <!-- 文本 -->
                  <div v-if="msg.model === 'mail.channel'" class="text">
                    <ChatText :message="msg" />
                  </div>

                  <div v-else>
                    <ChatOrder :message="msg" />
                  </div>

                  <!-- 图片 -->
                  <!-- <div class="text">
                  <img :src="" class="image" alt="聊天图片" />
                  </div> -->
                </div>
              </li>
            </ul>
            <!-- {{ messages }} -->
          </div>
        </div>
      </van-pull-refresh>

      <div>
        <!-- {{ channel }}
        <div v-for="ptn in channel.channel_partner_ids__objects" :key="ptn.id">
          {{ ptn.id }},{{ ptn.name }},{{ ptn.is_typing }},{{
            ptn.last_message_id
          }}
        </div> -->
      </div>

      <div fixed>
        <van-row :gutter="20">
          <van-col :span="18">
            <!-- type="textarea" -->

            <van-cell-group>
              <van-field
                v-model="chat"
                label=""
                placeholder="输入新消息"
                @keyup.enter.native="handleChat"
                @blur.native.capture="handleBlur"
                @focus.native.capture="handleFocus"
              />
            </van-cell-group>
          </van-col>
          <van-col :span="3">
            <van-button
              icon="comment-o"
              size="small"
              @click.native="handleChat"
            />
          </van-col>
          <van-col :span="3">
            <van-button icon="add-o" size="small" @click.native="handlePlus" />
          </van-col>
        </van-row>
      </div>

      <van-popup v-model="popupVisible" position="bottom">
        this is a popup 2
      </van-popup>
    </div>
  </div>
</template>

<script>
import { parseTime } from '@/utils'

import ChatText from './chatText'
import ChatOrder from './chatOrder'

// import { Toast } from 'vant'

export default {
  name: 'Message2',
  components: { ChatText, ChatOrder },

  data() {
    return {
      count: 0,
      isLoading: false,

      chat: '',
      popupVisible: false,
      inputPath: '/app/consult/survey-input'
    }
  },
  computed: {
    //
    channel: function() {
      return this.$store.state.appChat.channel
    },
    messages: function() {
      return this.$store.state.appChat.messages
    },

    isScroll: function() {
      return this.$store.state.appChat.isScroll
    },

    isEmployee: function() {
      return this.$store.state.user.isEmployee
    },

    user_partner_id: function() {
      return this.$store.state.user.partner_id
    }
  },

  watch: {
    messages: function() {
      if (this.isScroll) {
        this.scroll()
      }
    },

    'channel.is_typing': function(val) {
      this.$store.dispatch('header/set', {
        title: `${this.channel.name} ${val ? '正在输入' : '...............'}`
      })
    }
  },

  async created() {
    this.$store.dispatch('user/getInfo')

    // console.log('chat, qery', this.$route.query)

    const { id } = this.$route.query
    const channel_id = parseInt(id)
    await this.$store.dispatch('appChat/initChannel', channel_id)
    // console.log('channel,', this.channel)
    // console.log('messages,', this.messages)
  },

  mounted() {
    //
  },

  methods: {
    async onRefresh() {
      await this.$store.dispatch('appChat/fetchHistory')
      this.isLoading = false

      // setTimeout(() => {
      //   Toast('刷新成功')
      //   this.isLoading = false
      //   this.count++
      // }, 1000)
    },

    // 屏幕滚动
    scroll() {
      this.$nextTick(() => {
        // this.$refs.main.scrollTop = this.$refs.content.scrollHeight
      })
    },

    format_date(message) {
      const getNewDate = str => {
        return new Date(str.replace(/-/g, '/'))
      }

      const get_date_show = (date, date_last) => {
        //
        if (!date_last) {
          return date
        }

        // if (! getNewDate(date).getMinutes() % 10) {
        //   return date
        // }

        // console.log('xxxxx,message, ', message, date, date_last)

        if (getNewDate(date) - getNewDate(date_last) > 1000 * 60) {
          return date
        }

        return null
      }

      const index = this.messages.findIndex(item => item.id === message.id)
      const date_last = index ? this.messages[index - 1].date : null

      const date_show = get_date_show(message.date, date_last)

      if (!date_show) {
        return null
      }

      const dt2 = new Date(getNewDate(date_show).getTime() + 1000 * 60 * 60 * 8)

      const today = parseTime(new Date(), '{y}-{m}-{d}')
      const dt2_yyyymmdd = parseTime(dt2, '{y}-{m}-{d}')

      if (dt2_yyyymmdd === today) {
        return `今天 ${parseTime(dt2, '{h}:{i}')}`
      } else if (getNewDate(today) - getNewDate(dt2_yyyymmdd) === 86400000) {
        return `昨天 ${parseTime(dt2, '{h}:{i}')}`
      } else {
        return parseTime(dt2, '{y}-{m}-{d} {h}:{i}')
      }
    },

    get_image(msg) {
      const baseURL = process.env.VUE_APP_BASE_API
      const imgUrl = '/web/image'
      const image_url = `${baseURL}${imgUrl}?model=res.partner&id=${
        msg.author_id[0]
      }&field=image_1920`
      return image_url
    },

    align(row) {
      return row.author_id[0] === this.user_partner_id ? 'self' : 'other'
    },

    handleFocus() {
      console.log('xxxx, handleFocus')
      this.$store.dispatch('appChat/postNotifyTyping', true)
    },

    handleBlur() {
      console.log('xxxx, handleBlur')
      this.$store.dispatch('appChat/postNotifyTyping', false)
    },

    handleChat() {
      this.$store.dispatch('appChat/postMessage', this.chat)
      this.chat = ''
    },

    async handlePlus() {
      console.log('handlePlus')
      this.popupVisible = true

      //
      // if (this.whoAmI === 'customer') {
      //   const consultant_id = this.channel.partner_id
      //   const consultee_id = this.channel.me_partner_id
      //   console.log('handlePlus', this.whoAmI, consultant_id, consultee_id)
      //   this.post_consult_consultation({ consultant_id, consultee_id })
      //   // await this.find_regiter({ doctor_id, customer_id })
      // }
      // if (this.whoAmI === 'salesperson') {
      //   const consultee_id = this.channel.partner_id
      //   const consultant_id = this.channel.me_partner_id
      //   console.log('handlePlus', this.whoAmI, consultant_id, consultee_id)
      //   this.post_consult_survey({ consultant_id, consultee_id })
      //   // await this.find_regiter({ doctor_id, customer_id })
      // }
      // const SO = this.Model.env('sale.order')
      // const res = await SO.search({ fields: { name: null } })
      // const order_id = res[0].id
      // this.create_question_order()
      // const SO = this.Model.env('sale.order.template')
      // console.log('handlePlus 2', res2)
      // this.popupVisible = true
      // this.Model.private_message_post(this.channel.id, this.chat)
      // this.chat = ''
    }
  }
}
</script>

<style type="text/css">
.message {
  width: 100%;
  height: 500px;
  padding: 10px;
  box-sizing: border-box;
  /* background-color: pink; */
  background-color: #f5f5f5;
  overflow: auto;
}
.message li {
  margin-bottom: 15px;
  left: 0;
  position: relative;
  display: block;
}

.message .time {
  margin: 10px 0;
  text-align: center;
}

.message .time > span {
  display: inline-block;
  padding: 0 5px;
  font-size: 12px;
  color: #fff;
  border-radius: 2px;
  background-color: #dadada;
}
.message .self {
  text-align: right;
}
.message .self .avatar {
  float: right;
  margin: 0 0 0 10px;
}
.message .self .text {
  background-color: #9eea6a;
}

.message .self .text:before {
  right: inherit;
  left: 100%;
  border-right-color: transparent;
  border-left-color: #9eea6a;
}

.message .other {
  text-align: left;
}
.message .other .avatar {
  float: left;
  margin: 0 0 0 10px;
}

.message .other .text {
  background-color: #9eea6a;
}

.message .other .text:before {
  left: inherit;
  right: 100%;
  border-left-color: transparent;
  border-right-color: #9eea6a;
}

.an-move-left {
  left: 0;
  animation: moveLeft 0.7s ease;
  -webkit-animation: moveLeft 0.7s ease;
}
.an-move-right {
  left: 0;
  animation: moveRight 0.7s ease;
  -webkit-animation: moveRight 0.7s ease;
}
</style>
